package com.example.demo4

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.example.demo4.model.Card

class CardView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    
    private var card: Card? = null
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    
    init {
        paint.style = Paint.Style.FILL
        textPaint.style = Paint.Style.FILL
        textPaint.textAlign = Paint.Align.CENTER
        textPaint.textSize = 48f
        setBackgroundColor(Color.WHITE)
    }
    
    fun setCard(card: Card) {
        this.card = card
        invalidate()
    }
    
    fun getCard(): Card? = card
    
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        
        val card = this.card ?: return
        
        // 绘制边框
        paint.style = Paint.Style.STROKE
        paint.color = Color.BLACK
        paint.strokeWidth = 3f
        canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)
        
        // 绘制背景
        paint.style = Paint.Style.FILL
        
        when {
            card.isMatched -> {
                // 已配对 - 绿色背景
                paint.color = Color.parseColor("#90EE90")
                canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)
            }
            card.isChosen -> {
                // 已选中 - 显示卡牌内容
                paint.color = Color.WHITE
                canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)
                
                // 绘制卡牌文字
                textPaint.color = when {
                    card.toString().contains("♥") || card.toString().contains("♦") -> Color.RED
                    else -> Color.BLACK
                }
                
                val text = card.toString()
                val x = width / 2f
                val y = height / 2f - (textPaint.descent() + textPaint.ascent()) / 2
                canvas.drawText(text, x, y, textPaint)
            }
            else -> {
                // 未选中 - 显示背面（蓝色背景加X）
                paint.color = Color.parseColor("#4169E1")
                canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)
                
                // 绘制X标记
                paint.color = Color.WHITE
                paint.strokeWidth = 5f
                paint.style = Paint.Style.STROKE
                val margin = 15f
                canvas.drawLine(margin, margin, width - margin, height - margin, paint)
                canvas.drawLine(width - margin, margin, margin, height - margin, paint)
            }
        }
    }
}

